<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form
          ref="searchForm"
          :model="searchForm"
          inline
          :label-width="70"
          class="search-form"
        >
          <Form-item label="关键字" prop="keyword">
            <Input
              type="text"
              v-model="searchForm.keyword"
              placeholder="请输入关键字"
              clearable
              style="width: 200px"
            />
          </Form-item>
          <Form-item label="手机号" prop="phoneNumber">
            <Input
              type="text"
              v-model="searchForm.phoneNumber"
              placeholder="请输入手机号"
              :maxlength="11"
              clearable
              style="width: 200px"
            />
          </Form-item>
          <Form-item label="部门" prop="deptName">
            <Select
              v-model="searchForm.deptName"
              placeholder="请选择"
              clearable
              style="width: 200px"
            >
              <Option v-for="(item, index) in deptList" :key="index" :value="item">{{
                item
              }}</Option>
            </Select>
          </Form-item>
          <Button
            @click="handleSearch"
            class="search-btn"
            type="primary"
            icon="ios-search"
            >搜索</Button
          >
        </Form>
      </Row>
      <Row class="operation padding-row">
        <Button @click="handleAdd" type="primary">新增</Button>
        <Button @click="handleImport">导入</Button>
        <Button @click="handleExport">导出</Button>
        <Button @click="batchDel">批量删除</Button>
        <Button @click="resetPwd">重置密码</Button>
        <Button @click="asyncData">同步数据</Button>
      </Row>
      <Table
        :loading="loading"
        border
        :columns="columns"
        sortable="custom"
        class="mt_10"
        :data="data"
        ref="table"
        @on-selection-change="changeSelect"
      ></Table>
      <Row type="flex" justify="end" class="mt_10">
        <Page
          :current="searchForm.pageNumber"
          :total="total"
          :page-size="searchForm.pageSize"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
          :page-size-opts="[10, 20, 50]"
          size="small"
          show-total
          show-elevator
          show-sizer
        ></Page>
      </Row>
    </Card>

    <!-- 新增、编辑模态框 -->
    <Modal v-model="editFlag" :title="editAction == 'add' ? '新增' : '编辑'">
      <Form ref="editForm" :model="editForm" :rules="rules" :label-width="80">
        <FormItem label="工号" prop="teacherId" style="width: 100%">
          <Input v-model="editForm.teacherId" type="number" placeholder="请输入工号" />
        </FormItem>
        <FormItem label="手机号" prop="phoneNumber" style="width: 100%">
          <Input
            v-model="editForm.phoneNumber"
            :maxlength="11"
            placeholder="请输入手机号"
          />
        </FormItem>
        <FormItem
          label="密码"
          v-if="editAction == 'add'"
          prop="password"
          style="width: 100%"
        >
          <Input type="password" v-model="editForm.password" placeholder="请输入密码" />
        </FormItem>
        <FormItem label="姓名" prop="name" style="width: 100%">
          <Input v-model="editForm.name" :maxlength="10" placeholder="请输入姓名" />
        </FormItem>
        <FormItem label="部门" prop="deptName" style="width: 100%">
          <Input v-model="editForm.deptName" placeholder="请输入部门" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="editFlag = false">取消</Button>
        <Button type="primary" @click="submitForm">确定</Button>
      </div>
    </Modal>
    <Modal v-model="importFlag" title="导入">
      <Form :label-width="80">
        <FormItem label="下载模板" style="width: 100%">
          <Button type="primary" @click="handleDownload">下载模板</Button>
        </FormItem>
        <FormItem label="上传文件" style="width: 100%">
          <Upload
            action
            type="drag"
            :max-size="10 * 1024"
            accept=".xls, .xlsx"
            :format="['xls', 'xlsx']"
            :before-upload="handleUpload"
          >
            <div v-if="uploading" class="spin-upload">
              <Spin fix>
                <Icon type="ios-loading" size="18" class="spin-loading"></Icon>
                <div>上传中</div>
              </Spin>
            </div>
            <div v-else class="spin-upload">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>将文件拖到此处，或点击上传</p>
            </div>
          </Upload>
          <p>可上传.xls，.xlsx格式文件，且不超过10MB</p>
          <p style="color: red">注意：文件必上传，一次只能上传一个文件</p>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="importFlag = false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import * as API_Person from "@/api/person.js";
import * as RegExp from "@/libs/RegExp.js";

export default {
  name: "person-teacher",
  data() {
    return {
      loading: false, // 加载状态
      uploading: false, // 上传状态
      searchForm: {
        // 请求参数
        pageNumber: 1,
        pageSize: 10,
        keyword: "", //关键字
        phoneNumber: "", //手机号
        deptName: "", //部门
      },
      selectList: [], // 多选数据
      deptList: [], // 部门列表
      editFlag: false, // 编辑弹窗
      editForm: {}, // 编辑表单
      editAction: "add", // 弹窗操作
      editAction: "add", // 弹窗操作
      importFlag: false, //导入弹窗
      rules: {
        // 验证规则
        teacherId: [{ required: true, message: "请输入工号" }],
        phoneNumber: [
          { required: true, message: "请输入手机号码" },
          {
            pattern: RegExp.mobile,
            message: "请输入正确的手机号",
          },
        ],
        name: [{ required: true, message: "请输入姓名" }],
        password: [{ required: true, message: "请输入密码" }],
        deptName: [{ required: true, message: "请输入部门" }],
      },
      columns: [
        // 表头
        { type: "selection", width: 60, align: "center" },
        { title: "工号", key: "teacherId", width: 200, tooltip: true },
        { title: "姓名", key: "name", width: 300, tooltip: true },
        { title: "身份证号", key: "idCard", width: 300, tooltip: true },
        { title: "手机号", key: "phoneNumber", width: 300, tooltip: true },
        { title: "部门", key: "deptName", width: 200, tooltip: true },
        {
          title: "状态",
          minWidth: 120,
          render: (h, params) => {
            return h("div", [
              h("div", {
                style: {
                  display: "inline-block",
                  width: "8px",
                  height: "8px",
                  backgroundColor: params.row.status ? "#68CABE" : "#FF5C58",
                  marginRight: "6px",
                  borderRadius: "50%",
                },
              }),
              h("span", {}, params.row.status ? "启用" : "禁用"),
            ]);
          },
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          width: 200,
          fixed: "right",
          render: (h, params) => {
            return h(
              "div",
              {
                style: { display: "flex", justifyContent: "center" },
              },
              [
                h(
                  "Button",
                  {
                    props: { type: "primary", size: "small" },
                    style: { marginRight: "5px" },
                    on: {
                      click: () => {
                        this.handleEdit(params.row);
                      },
                    },
                  },
                  "编辑"
                ),
                h(
                  "Button",
                  {
                    props: { size: "small" },
                    style: { marginRight: "5px" },
                    on: {
                      click: () => {
                        this.handleStatus(params.row);
                      },
                    },
                  },
                  params.row.status ? "禁用" : "启用"
                ),
                h(
                  "Button",
                  {
                    props: { size: "small", type: "error" },
                    style: { marginRight: "5px" },
                    on: {
                      click: () => {
                        this.handleDel(params.row);
                      },
                    },
                  },
                  "删除"
                ),
              ]
            );
          },
        },
      ],
      data: [], // 表单数据
      total: 0, // 表单数据总数
    };
  },
  watch: {
    importFlag(v) {
      if (!v) this.uploading = false;
    },
  },
  methods: {
    // 分页 改变页码
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getData();
    },
    // 分页 改变页数
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.searchForm.pageNumber = 1;
      this.getData();
    },
    // 搜索
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getData();
    },
    // 多选
    changeSelect(e) {
      this.selectList = e;
    },
    // 新增
    handleAdd() {
      this.editAction = "add";
      this.editForm = {
        id: "",
        teacherId: "",
        name: "",
        password: "",
        phoneNumber: "",
        deptName: "",
        idCard: "",
        status: true,
      };
      this.$refs.editForm.resetFields();
      this.editFlag = true;
    },
    // 修改
    handleEdit(val) {
      this.editAction = "edit";
      this.editForm = {
        id: val.id,
        teacherId: val.teacherId,
        name: val.name,
        phoneNumber: val.phoneNumber,
        deptName: val.deptName,
        idCard: val.idCard,
        status: val.status,
      };
      this.editFlag = true;
    },
    // 导入
    handleImport() {
      this.importFlag = true;
    },
    // 导出
    handleExport() {
      let url = "/passport/teacher/export";
      let params = Object.assign({}, this.searchForm);
      delete params.pageNumber;
      delete params.pageSize;
      API_Person.postExport(url, params).then((res) => {
        if (res.status == 200) {
          let fileName = res.headers["content-disposition"]?.split(";")[1];
          let name = decodeURIComponent(fileName).split("=")[1];
          this.download(name, res.data);
          this.$Message.success({
            content: "导出成功",
            duration: 10,
          });
        }
      });
    },
    // 下载
    download(name, data) {
      let blob = new Blob([data], { type: "application/octet-stream" });
      let url = window.URL.createObjectURL(blob);
      let alink = document.createElement("a");
      alink.setAttribute("href", url);
      alink.setAttribute("download", name);
      alink.click();
    },
    // 同步统一登录数据
    asyncData() {
      API_Person.getAsyncTeachData().then((res) => {
        if (res.success) {
          this.$Message.success("数据同步中，预计需要5~10分钟");
        }
      });
    },
    // 手动上传
    handleUpload(file) {
      let typeList = [".xls", ".xlsx"];
      if (!typeList.some((i) => file.name.lastIndexOf(i) != -1)) {
        this.$Message.warning("请检查上传文件格式");
        return;
      }
      if (file.size / 1024 > 10 * 1024) {
        this.$Message.warning("文件大小不能超过10MB");
        return;
      }
      this.uploading = true;
      const formData = new FormData();
      formData.append("file", file);
      API_Person.postImportTeacher(formData)
        .then((res) => {
          if (res.success) {
            this.$Message.success("导入成功");
            this.getData();
            this.importFlag = false;
          }
        })
        .finally(() => {
          this.uploading = false;
        });
      return false;
    },
    // 删除
    handleDel(v) {
      this.$Modal.confirm({
        title: "确认删除",
        content: "<p>您确认要删除用户" + v.name + "？</p>",
        onOk: () => {
          API_Person.delTeacher(v.id).then((res) => {
            if (res.success) {
              this.$Message.success("删除成功");
              this.getData();
            }
          });
        },
      });
    },
    // 批量删除
    batchDel() {
      if (this.selectList.length) {
        this.$Modal.confirm({
          title: "确认删除",
          content: "<p>您确认要删除验所选的" + this.selectList.length + "条数据？</p>",
          onOk: () => {
            let ids = this.selectList
              .map((i) => {
                return i.id;
              })
              .join(",");
            API_Person.delTeacher(ids).then((res) => {
              if (res.success) {
                this.$Message.success("删除成功");
                this.getData();
              }
            });
          },
        });
      } else {
        this.$Message.warning("请先勾选数据");
      }
    },
    // 重置密码
    resetPwd() {
      if (this.selectList.length) {
        this.$Modal.confirm({
          title: "确认重置",
          content:
            "<p>您确认要重置所选的" +
            this.selectList.length +
            "条用户数据密码为【123456】？</p>",
          onOk: () => {
            let mobiles = this.selectList
              .map((i) => {
                return i.phoneNumber;
              })
              .join(",");
            API_Person.postTeacherResetPassword(mobiles).then((res) => {
              if (res.success) {
                this.$Message.success("重置成功");
                this.getData();
              }
            });
          },
        });
      } else {
        this.$Message.warning("请先勾选数据");
      }
    },
    // 查询教师列表
    getData() {
      this.loading = true;
      API_Person.getTeacherPage(this.searchForm)
        .then((res) => {
          if (res.success) {
            this.data = res.result.records;
            this.total = parseInt(res.result.total);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 提交
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.editAction == "add") {
            this.editForm.password = this.md5(this.editForm.password);
            API_Person.postAddTeacher(this.editForm).then((res) => {
              if (res.success) {
                this.$Message.success("新增成功");
                this.editFlag = false;
                this.getData();
              }
            });
          } else {
            API_Person.putUpdateTeacher(this.editForm).then((res) => {
              if (res.success) {
                this.$Message.success("编辑成功");
                this.editFlag = false;
                this.getData();
              }
            });
          }
        }
      });
    },
    // 下载模板
    handleDownload() {
      let params = { templateName: "teacher" };
      API_Person.getTemplateInfo(params).then((res) => {
        if (res.success) {
          window.location.href = res.result;
          this.$Message.info({
            content: "请注意表格规范，填写异常的数据将不被保存",
            duration: 10,
          });
        }
      });
    },
    // 禁-启用教师用户状态
    handleStatus(v) {
      let params = {
        id: v.id,
        status: !v.status,
      };
      this.$Modal.confirm({
        title: "确认禁用" + v.status ? "禁用" : "启用",
        content:
          "<p>您确认要" + (v.status ? "禁用" : "启用") + "用户" + v.name + "？</p>",
        onOk: () => {
          API_Person.putTeacherStatus(params).then((res) => {
            if (res.success) {
              this.$Message.success((v.status ? "禁用" : "启用") + "成功");
              this.getData();
            }
          });
        },
      });
    },
    // 获取部门列表
    getDeptList() {
      API_Person.getDeptList().then((res) => {
        if (res.success) {
          this.deptList = res.result;
        }
      });
    },
  },
  mounted() {
    this.getData();
    this.getDeptList();
  },
};
</script>
<style lang="scss" scoped>
::v-deep .ivu-table-wrapper {
  width: 100%;
}
::v-deep .ivu-card {
  width: 100%;
}
.spin-loading {
  animation: ani-loading 1s linear infinite;
}
@keyframes ani-loading {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.spin-upload {
  height: 130px;
  position: relative;
  border: 1px solid #eee;
  padding: 20px 0;
  position: relative;
}
</style>
